package lookas.track;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBFactory{

    private static Connection  connection;
    private static String      file  = "./iGO_backup.db";
    public static final String TABLE = "tree";

    public static Connection getConnection() throws SQLException,
        RuntimeException, IOException{

        File tmpF = new File(file);
        if(!tmpF.exists())
            throw new IOException("File " + tmpF.getAbsolutePath()
                + " doesn't exists.");

        if(connection == null){
            try{
                Class.forName("org.sqlite.JDBC");
            }catch(ClassNotFoundException e){
                throw new RuntimeException(e);
            }
            connection = DriverManager.getConnection("jdbc:sqlite:" + file);
        }
        return connection;
    }

    public static PreparedStatement prepareStatement(String sql)
        throws SQLException, IOException{

        return DBFactory.getConnection().prepareStatement(sql);
    }

    public static void setFile(String file){
        DBFactory.file = file;
    }

    public static void close() throws SQLException{
        connection.close();
    }
}
